#!encoding:utf-8


import sys
import sys
import os
import hmac
import hashlib
import time
sha256_key = '123456'
fromdir = '/Users/forke/Documents/project/_project/python/cutFile/out'
todir = '/Users/forke/Documents/project/_project/python/cutFile/out1'
todir2 = '/Users/forke/Documents/project/_project/python/cutFile/out2'


def joinfile(filename):
    if not os.path.exists(todir2):
        os.mkdir(todir2)
    if not os.path.exists(todir):
        print('Wrong directory')
    outfile = open(os.path.join(todir2, filename), 'wb')
    files = os.listdir(todir)  # list all the part files in the directory
    files.sort()  # sort part files to read in order
    for file in files:
        print file
        if "." not in file:
            filepath = os.path.join(todir, file)
            infile = open(filepath, 'rb')
            data = infile.read()
            outfile.write(data)
            infile.close()
    outfile.close()


def file_sha256(filepath):
    '''
    sha256加密
    return:加密结果转成16进制字符串形式，并大写
    '''
    infile = open(filepath, 'rb')
    data = infile.read()
    hsobj = hashlib.sha256(data)
    infile.close()
    return hsobj.hexdigest().upper()


def checkFile():
    files = os.listdir(fromdir)  # list all the part files in the directory
    files.sort()  # sort part files to read in order
    for file2 in files:
        # 取出文件的前80位
        file2 = os.path.join(fromdir, file2)
        with open(file2) as file:
            len_80s = file.read(80)
            # print(type(len_80s))
            len_80 = str(len_80s)
            sha256_key = len_80[0: 64]
            size = len_80[64:72]
            id = len_80[72: 80]
            content = file.read()
            createFile(id, content)
            filepath2 = os.path.join(todir, id)
            str_256 = file_sha256(filepath2)
            #print (str_256)
            size2 = os.path.getsize(filepath2)

            if(sha256_key == str_256 and int(size2) == int(size)):
                # return [True, id]
                print("1")
            else:
                # return [False, 0]
                print("2")


def createFile(filename, data):
    #print (filename)
    filePath = os.path.join(todir, filename)
    with open(filePath, "w+") as f:
        f.seek(0)
        f.write(data)
        f.close()


if __name__ == '__main__':
    # fromdir = input('Directory containing part files?')
    # filename = input('Name of file to be recreated?')
    # todir = input('Directory to store recreated file?')
    start = time.clock()
    filename = 'a'
    try:
        checkFile()
        joinfile(filename)
    except:
        print('Error joining files:')
        print(sys.exc_info()[0], sys.exc_info()[1])

    elapsed = (time.clock() - start)
    print("Time used:", elapsed)
